package com.yby6.framework.fastdfs;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.yby6.common.utils.StringUtils;
import com.yby6.framework.config.properties.QiniuOssProperties;
import com.yby6.system.domain.Attachment;
import com.yby6.system.service.AttachmentService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.yby6.common.utils.context.IdWorker;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * fast dfs 分步式文件上传
 * @author TeouBle
 */
@Service
@EnableConfigurationProperties(UploadProperties.class)
public class UploadService {

    private Log log= LogFactory.getLog(UploadService.class);

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private UploadProperties prop;

    @Autowired
    private HttpServletRequest httpServletRequest;

    @Autowired
    private AttachmentService attachmentService;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private QiniuOssProperties qiniuOssProperties;

    /**
     * 绝对路径
     * @param file
     * @param fileName
     * @return
     */
    public Attachment uploadImage(MultipartFile file, String fileName) {
        // 1、校验文件类型
        if (StringUtils.isBlank(fileName)){
            fileName = "杨不易呀";
        }
        String contentType = file.getContentType();
        if (!prop.getAllowTypes().contains(contentType)) {
            throw new RuntimeException("文件类型不支持");
        }
        // 2、校验文件内容
        try {
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image == null || image.getWidth() == 0 || image.getHeight() == 0) {
                throw new RuntimeException("上传文件有问题");
            }
        } catch (IOException e) {
            log.error("校验文件内容失败....{}", e);
            throw new RuntimeException("校验文件内容失败"+e.getMessage());
        }

        try {
            // 3、上传到FastDFS
            // 3.1、获取扩展名
            String extension = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
            // 3.2、上传
            // 开始绘制水印
            /*String[] contents = new String[] {"拍摄时间:" + DateUtils.parseDate(new Date()),"地址:" + AddressUtils.getRealAddressByIP(IpUtils.getIpAddr(httpServletRequest))};
            InputStream inputStream = ImageUtil.markImageByText(file,contents);*/
            StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), extension, null);
            // 开始存储数据库
            Attachment attachment = new Attachment();
            attachment.setId(idWorker.nextId());
            attachment.setTitle(file.getOriginalFilename());
            attachment.setName(fileName);
            attachment.setUrl(prop.getBaseUrl() + storePath.getFullPath());
            attachment.setShowUrl(prop.getBaseUrl() + storePath.getFullPath());

            attachmentService.insert(attachment);
            return attachment;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【文件上传】上传文件失败！....{}", e);
            throw  new RuntimeException("【文件上传】上传文件失败！"+e.getMessage());
        }
    }

    /**
     * 返回相对路径
     * @param file
     * @return
     */
    public String uploadImageReRPath(MultipartFile file) {
        // 1、校验文件类型
        String contentType = file.getContentType();
        if (!prop.getAllowTypes().contains(contentType)) {
            throw new RuntimeException("文件类型不支持");
        }
        // 2、校验文件内容
        try {
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image == null || image.getWidth() == 0 || image.getHeight() == 0) {
                throw new RuntimeException("上传文件有问题");
            }
        } catch (IOException e) {
            log.error("校验文件内容失败....{}", e);
            throw new RuntimeException("校验文件内容失败"+e.getMessage());
        }

        try {
            // 3、上传到FastDFS
            // 3.1、获取扩展名
            String extension = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
            // 3.2、上传
            StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), extension, null);
            // 返回路径
            return storePath.getFullPath();
        } catch (IOException e) {
            log.error("【文件上传】上传文件失败！....{}", e);
            throw  new RuntimeException("【文件上传】上传文件失败！"+e.getMessage());
        }
    }

    /**
     * 删除图片 相对路径 /group/**
     * @param path
     * @return
     */
    public void deleteFile(String path) {
        if(StringUtils.isNotBlank(path)){
            try {
                log.info("删除文件路径:" + path);
                storageClient.deleteFile(path.substring(path.indexOf("group1")));
                log.info("【文件删除成功】："+path);
            } catch (Exception e) {
                log.error("【文件删除失败】：", e);
                throw  new RuntimeException("【文件上传】上传文件失败！"+e.getMessage());
            }
        }
    }

    /**
     * 返回路径
     * @param file
     * @return
     */
    public String qiniuOssUploadFile(MultipartFile file) {
        //构造一个带指定Region对象的配置类
        Configuration cfg = new Configuration(qiniuOssProperties.getRegion());
        //创建文件上传的管理器
        UploadManager uploadManager = new UploadManager(cfg);
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String fileName = file.getOriginalFilename();
        //统一文件到日文件夹
        String key = DateUtil.today() + "/" + IdUtil.simpleUUID() + "-" + "yangbuyiya";
        try {
            byte[] uploadBytes = file.getBytes();
            // 获取文件流
            InputStream input = new ByteArrayInputStream(uploadBytes);
            //创建一个认证的对象
            Auth auth = Auth.create(qiniuOssProperties.getAccessKey(), qiniuOssProperties.getSecretKey());
            //获取token
            String upToken = auth.uploadToken(qiniuOssProperties.getBucket());
            // 需传递token进行文件上传
            Response response = uploadManager.put(input, key, upToken, null, null);
            //解析上传成功的结果
            DefaultPutRet defaultPutRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
            // 返回路径
            // qiniuOssProperties.getUrl() + defaultPutRet.hash
            defaultPutRet.key = qiniuOssProperties.getUrl() + defaultPutRet.key;
            defaultPutRet.hash = qiniuOssProperties.getUrl() + defaultPutRet.hash;
            return defaultPutRet.key;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "";
    }
}
